import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'
import layout from '../views/index'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject){
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)


const router = new VueRouter({
    routes: [
        {
            name:'my-login',
            path:'/',
            component:()=>import('@/views/login')
        },
        {
            name: 'my-layout',
            path: '/index',
            component: layout,
            meta: {
                requireAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
            },
        },
        {
            name:'item-info',
            path:'/iteminfo',
            component:()=> import('@/views/ItemsInfo')
        },
        {
            name:'cgpItems-info',
            path:'/cgpItems',
            component:()=>import('@/views/chargingPileItemsInfo')
        },
        {
            name:'statisti-c',
            path:'/statistic',
            component:()=>import('@/views/statistic')
        },
        {
            name:'my-map',
            path:'/mymap',
            component:()=>import('@/components/map')
        }

    ],
    made: 'history',
    base: process.env.BASE_URL
})



router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
        if (localStorage.getItem('token')) {  // 通过vuex state获取当前的token是否存在
            next();
        }
        else {
            next({
                path: '/',
                query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
            })
        }
    }
    else {
        next();
    }
})


export default router